<template>
  <div class="wrapper w-full h-full">
    <canvas id="canvas" />
    <Loading />
    <TipBar />
  </div>
</template>
<script setup lang="ts">
import {
  AnimationMixer,
  Box3,
  Clock,
  Color,
  Object3D,
  Scene,
  Group,
} from "three";
import { onMounted } from "vue";
import Loading from "../components/Loading.vue";
import InitScene from "../utils/InitScene";
import { DefaultLoaderanager } from "../utils/LoaderManager";
import TipBar from "../components/TipBar.vue";
import { DefaultSelectOperate } from "../utils/SelectOperate";

let canvas: HTMLCanvasElement | null;
let scene: Scene;
const defaultInitScene = new InitScene();
const clock = new Clock();
let animationMixer: AnimationMixer;
const urls: string[] = ["island/scene.gltf", "walk/scene.gltf"];
let sceneGroup: Group = new Group();

onMounted(() => {
  canvas = document.querySelector("#canvas");
  if (!canvas) return;
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  defaultInitScene.init(canvas);
  defaultInitScene.scene.background = new Color("#5de9ff");
  document
    .querySelector(".wrapper")
    ?.appendChild(defaultInitScene.renderer.domElement);
  scene = defaultInitScene.scene;
  scene.background = new Color("#D6D7D8");
  DefaultLoaderanager.load(urls).addEventListener("loaded", (e) => {
    let data = e.data;
    for (let item in data) {
      let scene = data[item].scene;
      if (item.includes("walk")) {
        scene.scale.set(0.01, 0.01, 0.01);
        scene.position.set(1, 16, 1);
        let mesh = data[item];
        animationMixer = new AnimationMixer(scene);
        const animationClip = mesh.animations[0];
        const action = animationMixer.clipAction(animationClip);
        action.play();
      }
      sceneGroup.add(setSceneCenter(scene));
    }
    sceneGroup.position.y += 40;
    sceneGroup.position.z += 70;
    sceneGroup.rotation.y -= Math.PI * 0.2;
    sceneGroup.rotation.x -= Math.PI * 0.05;
    sceneGroup.rotation.z -= Math.PI * 0.02;
    defaultInitScene.scene.add(sceneGroup);
  });

  defaultInitScene.addEventListener("animate", () => {
    animationMixer && animationMixer.update(clock.getDelta());
  });
  defaultInitScene.renderer.domElement.addEventListener("mousemove", (e) => {
    DefaultSelectOperate.handleMouse(
      e.clientX,
      e.clientY,
      defaultInitScene.camera,
      defaultInitScene.scene
    );
  });
});
function setSceneCenter(scene: Object3D): Object3D {
  let box = new Box3().setFromObject(scene); // 获取模型的包围盒
  let mdlen = box.max.x - box.min.x; // 模型长度
  let mdwid = box.max.z - box.min.z; // 模型宽度
  let mdhei = box.max.y - box.min.y; // 模型高度
  let x1 = box.min.x + mdlen / 2; // 模型中心点坐标X
  let y1 = box.min.y + mdhei / 2; // 模型中心点坐标Y
  let z1 = box.min.z + mdwid / 2; // 模型中心点坐标Z
  scene.position.set(-x1, -y1, -z1); // 将模型进行偏移
  return scene;
}
</script>
